$(function() {
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/product_model.php';
	 
    
	if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	
	LoadData("",0);
	
	$("#btnSearch").click(function(){
		var _find_name = $("#txtName_s").val();
		var _type_name = $("#cbotype_s").val();
		
		LoadData(_find_name,_type_name);
	});
	
	$("#btnAdd").live('click', function(){
		$("#txtCode").removeAttr('disabled' );
		$("#txtName").val("");
		$("#txtCost").val("");
		$("#txtPrice").val("");
		$("#txtCode").val("");
		mode="add";
	});
	
	$.get(url, {"m":"c"},function(data){
			var obj=eval('('+data+')');	
			 
			if (obj != null){
				$.each(obj, function(index, text) {
					
					$("#cbotype").append(
							$('<option></option>').val(text).html(index)
						 );
					$("#cbotype_s").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	
	$("#cbotype_s").append($('<option></option>').val(0).html('-'));
	
	//Popup confirm delete
	$("#btnDelete").live('click', function(){
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		var id=row_id[1];
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id,"tb":"product"},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	$(".btnEdit").live('click',function(){
		mode="edit";
		$("#txtCode").attr('disabled','disabled');
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
		$("#txtCode").val(data[2]);
		$("#txtName").val(data[3]);
		$("#cboType").val(data[6]);
		$("#txtCost").val(data[4]);
		$("#txtPrice").val(data[5]);
		if (data[7]=='Y'){
			$("#chkY").attr('checked','checked');
		}else{
			$("#chkN").attr('checked','checked');
		}
	});
	$("#btnSave").live('click',function(){
		$("#txtName").jqBootstrapValidation({preventSubmit: false,
		submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
 
		var _name = $.trim($("#txtName").val());
		var _type = $.trim($("#cbotype").val());
		var _cost = $.trim($("#txtCost").val());
		var _price = $.trim($("#txtPrice").val());
		var _code = $("#txtCode").val();
		var dataSet;
		 
		if (mode=="add"){
			dataSet={"m":"add","name":_name,"type":_type,"code":_code,"cost":_cost,"price":_price,"s":$('input[name=chk]:checked').val()};  
		}else{
			dataSet={"m":"edit","id":m_id,"name":_name,"code":_code,"type":_type,"cost":_cost,"price":_price,"s":$('input[name=chk]:checked').val()};  
		}
		
		if (_name!=""){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					 
					if (data!=0){
						$("#popup").modal('hide');
						LoadData("",0);
					}else{
						alert("รหัสพัสดุซ้ำ");
						$("#txtCode").focus();
					}
				}
			});
			
		}
		 $("#txtName").jqBootstrapValidation("destroy");
	});
	
	$(".btnDel").live('click',function(){
		 
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);
 
	});
	
    function LoadData(s_name, s_type){
        $( "#resultData tbody tr" ).remove();
 
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bLengthChange": false,
			 "bAutoWidth": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"name","value":s_name},
								{"name":"type","value":s_type});
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{   "bSortable": true, "aTargets": [ 2 ] },	
				{   "bSortable": true, "aTargets": [ 3 ] },	
				{   "bVisible": false, "aTargets": [ 4 ] },	
				{   "bVisible": false, "aTargets": [ 5 ] },	
				{   "bSortable": true, "aTargets": [ 6 ] },	
 
				{   "bSortable": true, "aTargets": [ 7 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (data=='Y')
							tmp="<font style='color:green !important;'>ใช้งาน</font>";
						else
							tmp="<font style='color:red !important;'>ยกเลิก</font>";
						return tmp;}
				},
				{ "aTargets": [ 8 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_it==1)
							return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else
							return "";
					}
				},
				{"aTargets": [ 9 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_te==1){
						return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						}else{
						return "";}
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 
			/* Need to redo the counters if filtered or sorted */
			     var oSettings = this.fnSettings();
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=iTotalRecords ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		 } );
		 
      }
	  $("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});
    
});


